<template>
  <div class="app-container">
    <el-tabs v-model="activityType" @tab-click="handleClick">
      <el-tab-pane
        v-for="item in menuList"
        :key="item.id"
        :label="item.menuName"
        :name="String(item.id)"
      ></el-tab-pane>
    </el-tabs>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="主题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入主题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="currentStatus">
        <el-select
          v-model="queryParams.currentStatus"
          placeholder="状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in statusList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="onAdd">新增</el-button>
    <el-table v-loading="loading" :data="tableData">
      <el-table-column prop="title" label="主题"  show-overflow-tooltip></el-table-column>
      <el-table-column prop="sort" label="排序" align="center"></el-table-column>
      <el-table-column label="WAP端封面" align="center">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.wapImgUrl"
            style="width: 80px; height: 80px"
            :src="baseUrl + scope.row.wapImgUrl"
            fit="cover"
            :preview-src-list="[baseUrl + scope.row.wapImgUrl]"
          >
            <div slot="error" class="image-slot" style="width: 80px; height: 80px; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #999;">
              暂无图片
            </div>
          </el-image>
          <span v-else style="color: #999;">暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="PC端封面" align="center">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.pcImgUrl"
            style="width: 80px; height: 80px"
            :src="baseUrl + scope.row.pcImgUrl"
            fit="cover"
            :preview-src-list="[baseUrl + scope.row.pcImgUrl]"
          >
            <div slot="error" class="image-slot" style="width: 80px; height: 80px; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #999;">
              暂无图片
            </div>
          </el-image>
          <span v-else style="color: #999;">暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="视频上传" align="center">
        <template slot-scope="scope">
          <el-link
            v-if="scope.row.fileUrl"
            :href="baseUrl + scope.row.fileUrl"
            target="_blank"
            type="primary"
            :underline="false"
          >
            {{ baseUrl + scope.row.fileUrl }}
          </el-link>
          <span v-else style="color: #999;">暂无视频</span>
        </template>
      </el-table-column>
      <el-table-column label="内容介绍" prop="contentIntroduce"  show-overflow-tooltip>
        <template slot-scope="scope">
          <div v-html="scope.row.contentIntroduce" style="max-height: 60px; overflow: hidden;"></div>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right">
        <template v-slot="{ row }">
          <Actions
            :row="row"
            @onPublish="onPublish(row)"
            @onOffShelf="onOffShelf"
            @onEdit="onEdit"
            @onDetail="onDetail"
            @onDelete="onDelete"
          />
        </template>
      </el-table-column>
    </el-table>
    <!-- <pagination :total="pageParams.total" :page.sync="pageParams.pageNum" :limit.sync="pageParams.pageSize"
            @pagination="getPage" /> -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="visible"
      width="70%"
      :destroy-on-close="true"
    >
      <Add
        ref="AddForm"
        @success="onSuccess"
        @cancel="onCancel"
        :activityType="activityType"
      />
    </el-dialog>
    <el-dialog
      title="详情"
      :visible.sync="visibleDetail"
      width="70%"
      :destroy-on-close="true"
    >
      <Detail
        ref="Detail"
        :activityType="activityType"
        @cancel="onCancelDetail"
      />
    </el-dialog>

    <el-dialog
      title="提交一级审核"
      :visible.sync="open2"
      width="800px"
      append-to-body
    >
      <el-form ref="form" :model="form2" label-width="100px">
        <template>
          <el-tabs v-model="activeName" type="card">
            <el-tab-pane label="默认" name="first">
              <el-select v-model="form2.nextEmp" placeholder="请选择">
                <el-option
                  v-for="item in nextEmpList"
                  :key="item.userId"
                  :label="item.userId + '-' + item.userCnName"
                  :value="item.userId"
                >
                </el-option>
              </el-select>
            </el-tab-pane>
          </el-tabs>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="firstSubmit" type="primary">提交</el-button>
        <el-button @click="open2 = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  pageList,
  deleteById,
  listUsers,
  offShelf,
  audit,
} from "@/api/activityConfiguration";
import { getMenuTree, getListByParentId } from "@/api/activityMenu";
import Add from "./add.vue";
import Detail from "./detail.vue";
import { formatCurrStatus } from "./status";
import Actions from "./actions.vue";
export default {
  components: {
    Add,
    Detail,
    Actions,
  },
  data() {
    return {
      formatCurrStatus,
      showSearch: true,
      queryParams: {
        title: "",
        menuId: null, // 初始值设为 null，将在获取菜单数据后设置为第一个菜单的ID
        currentStatus: null
      },
      baseUrl: process.env.VUE_APP_BASE_API,
      // 添加活动菜单列表和缓存
      activityMenuList: [],
      activityMenuCache: {},
      pageParams: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      loading: false,
      tableData: [],
      visible: false,
      dialogTitle: "",
      visibleDetail: false,
      activityType: null, // 初始值设为 null，将在获取菜单数据后设置为第一个菜单的ID
      menuList: [],
      statusList: [
        {
          id: "1",
          name: "草稿",
        },
        {
          id: "2",
          name: "待一级审核",
        },
        {
          id: "3",
          name: "待二级审核",
        },
        {
          id: "4",
          name: "待发布",
        },
        {
          id: "5",
          name: "已发布",
        },
      ],
      open2: false,
      form2: {
        id: null,
        nextEmp: null,
      },
      activeName: "first",
      nextEmpList: [],
    };
  },
  created() {
    this.getMenuData();
  },
  mounted() {
    // 初始化活动类型为"活动预约"
    this.initActivityType();
  },
  methods: {
    initActivityType() {
      // 如果菜单列表已加载，使用第一个菜单的ID
      if (this.menuList && this.menuList.length > 0) {
        this.activityType = String(this.menuList[0].id);
        this.queryParams.menuId = String(this.menuList[0].id);
      } else {
        // 如果菜单列表还未加载，使用默认值
        this.activityType = "1";
        this.queryParams.menuId = null;
      }
    },
    getMenuData() {
      getMenuTree(1).then((res) => {
        if (res.code === 200 && res.data) {
          // 先创建活动预约选项卡
          this.menuList = [];
          
          // 处理后端返回的菜单数据，保持原有ID
          if (res.data && res.data.length > 0) {
            res.data.forEach(item => {
              this.menuList.push({
                id: String(item.id), // 确保ID是字符串类型
                menuName: item.menuName
              });
            });
            
            // 设置默认选中第一个tab（使用返回数据的第一个菜单ID）
            const firstMenuId = String(res.data[0].id);
            this.activityType = firstMenuId;
            this.queryParams.menuId = firstMenuId;
          } else {
            // 如果没有数据，使用默认值
            this.activityType = "1";
            this.queryParams.menuId = "1";
          }
        }
      }).catch((error) => {
        console.error("获取菜单数据失败:", error);
        // 即使获取菜单失败，也设置默认值
        this.menuList = [];
        this.activityType = "1";
        this.queryParams.menuId = null;
      }).finally(() => {
        // 无论成功或失败，都获取页面数据
        this.getPage();
      });
    },
    getPage() {
      // 直接使用当前标签页ID作为activityType参数
      const params = {
        ...this.queryParams,
        pageNum: this.pageParams.pageNum,
        pageSize: this.pageParams.pageSize,
        activityType:  this.activityType === "1" ? "1" : "2"
      };
      
      this.loading = true;
      pageList(params).then((res) => {
        this.tableData = res.data?.records;
        this.loading = false;
      });
    },
    statusFormat(row, column) {
      let str = "";
      this.statusList.map((item) => {
        if (item.id == row.currentStatus) {
          str = item.name;
        }
      });
      return str;
    },
    handleQuery() {
      this.getPage();
    },
    resetQuery() {
      // 保留当前选中的tab对应的菜单ID
      const currentMenuId = this.activityType;
      
      // 重置查询表单，只重置搜索相关参数
      this.queryParams = {
        title: "", // 清空主题
        menuId: currentMenuId, // 保持当前选中的tab对应的菜单ID
        currentStatus: null // 清空状态选择
      };
      
      // 获取数据
      this.getPage();
    },
    onAdd() {
      this.dialogTitle = "新增";
      this.visible = true;
    },
    onDelete(id) {
      this.$confirm("你确定要删除活动内容吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteById(id).then(() => {
          this.getPage();
        });
      });
    },
    async onPublish(row) {
      this.form2.id = row.id;
      this.form2.nextEmp = null;
      this.nextEmpList = [];

      let res = await listUsers("kb", "reviewer_l1");
      if (res.code == 200) {
        this.nextEmpList = res.data;
      }

      this.open2 = true;
    },
    async firstSubmit() {
      if (this.form2.nextEmp == null) {
        this.$alert("请选择审核人！", "提示", {
          confirmButtonText: "确定",
          type: "warning",
        });
        return;
      }

      let nextEmpName = this.nextEmpList.filter(
        (item) => item.userId == this.form2.nextEmp
      )[0].userCnName;

      let res = await audit(this.form2.id, this.form2.nextEmp, nextEmpName);
      if (res.code == 200) {
        this.$modal.msgSuccess("提交一级审核成功！");
        this.open2 = false;
        this.getPage();
      }
    },
    onOffShelf(id) {
      this.$confirm("你确认要下架活动内容吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        offShelf(id).then(() => {
          this.getPage();
        });
      });
    },
    onEdit(id) {
      this.dialogTitle = "编辑";
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["AddForm"].onDetail(id);
      });
    },
    onDetail(id) {
      this.visibleDetail = true;
      this.$nextTick(() => {
        this.$refs["Detail"].onDetail(id);
      });
    },
    onSuccess() {
      this.visible = false;
      this.getPage();
    },
    onCancel() {
      this.visible = false;
    },
    onCancelDetail() {
      this.visibleDetail = false;
    },
    handleClick(tab) {
      // 保证tabName是字符串类型
      const tabName = String(tab.name);
      
      // 设置当前选中的选项卡ID
      this.activityType = tabName;
      this.queryParams.menuId = tabName;
      
      // 如果不是互动体验标签页，加载对应的活动类型列表
      if (tabName !== "1") {
        this.loadActivityMenus(tabName);
      }
      
      // 获取数据
      this.getPage();
    },
    // 加载活动类型列表
    loadActivityMenus(parentId) {
      console.log('加载活动类型列表，parentId:', parentId);
      
      // 检查缓存中是否已有该parentId的数据
      if (this.activityMenuCache[parentId]) {
        console.log('使用缓存的活动类型列表');
        this.activityMenuList = this.activityMenuCache[parentId];
        return;
      }
      
      // 获取活动类型列表
      getListByParentId(parentId).then(res => {
        if (res.code === 200) {
          // 处理返回的rows数据，将menuName映射为label，id映射为value
          const menuList = (res.rows || []).map(item => ({
            label: item.menuName,
            value: item.id
          }));
          
          // 保存到缓存
          this.activityMenuCache[parentId] = menuList;
          this.activityMenuList = menuList;
          
          console.log('活动类型列表:', this.activityMenuList);
        } else {
          console.error('获取活动类型列表失败:', res.msg);
        }
      }).catch(error => {
        console.error('请求活动类型列表出错:', error);
      });
    },
  },
};
</script>
